/* eslint-disable max-lines */
/* eslint-disable react/jsx-handler-names */
/**
 * @description 指令下达
 * @author wangjianjun
 *
 * type-1 指令下达 2-指令编辑  3-簿记下达 4-簿记编辑 5-簿记指令详情 11-组合试算
 */

import React, { PureComponent } from 'react';
import { DATA_ENTRY, FormGroup, PrimaryC, PrimaryGhostC, codeType, ModalC, TableC, StepC } from '../../../comps';
import { fixedNum } from '../../../utils/utils';
import config from './config';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col, message, Modal } from 'antd';
import investmentTypeData from '../../../utils/enumeratedValues/investmentType';
import { calculateFee, uniqueKey } from '../../../utils/commonFunc';
import { connect } from 'dva';
import 'moment/locale/zh-cn';
import OrderC from '@/src/comps/business/orderC';

@Form.create()
@connect(({ stockOrderM, exchangeAgreement, isAccountConfiguredM, userM: user, portfolioTrialAddM, loading, trailM }) => ({
  stockOrderM,
  exchangeAgreement,
  isAccountConfiguredM,
  user,
  portfolioTrialAddM,
  loading,
  trailM,
  errorSetMsg: isAccountConfiguredM.msg,
}))
export default class InstructionSend extends PureComponent {
  static defaultProps = {
    onRef: () => {},
  };

  constructor(props) {
    super(props);
    this.state = {
      productId: null, // 产品编号
      portfolioId: null, // 组合编号
      tradingCode: null, // 证券代码
      exchangeCode: null, // 交易市场
      orderSide: null, // 委托方向
      direction: null, // 交易方向
      type: null, // 交易类型
      price: null, // 委托价格
      amount: null, // 委托数量
      totalPrice: null, // 金额
      remark: null, // 备注
      realOrderPrice: null, // 交易价格
      realOrderQty: null, // 交易数量
      firstExpenses: null, // 一级费用
      statusControl: {}, // 对应模块的
      secuabbr: null, // 证券简称
      id: null, // 用来簿计修改
      id2: null, // 用来簿计修改
      status: false, // 控制下达按钮disabled
      btnLoading: false,
      priceDisabled: false,
      queryItems: { exchangeCode: '101,105' },
      Span1: 8,
      Span2: 16,
      span3: '10px',
      span4: null,
      isCanOrder: true, // 是否可以下达 默认可以下达
      query: {},
      isShow: false,
      trailColumns: [], // 试算结果列表
      trailDataSource: [], // 试算结果数据
      trailModel: false, // 试算模态框
      productCode: undefined, // 产品code
      portfolioCode: undefined, // 组合code
      portfolioName: undefined, // 组合名称
      productName: undefined, // 产品名称
      investmentType: undefined, // 投资类型
      feeData: {
        // 费用自动计算条件
        productId: undefined,
        portfolioid: undefined,
        tradingCode: undefined,
        exchangecode: undefined,
        trademarket: 'jjpt',
        sectype: 'stock',
        sectypeii: 'a',
        orderside: undefined,
        price: undefined,
      },
      uid: '',
      orderSideType: '1',
      visibleStep: false, // 下达状态是否可见
      orderParams: undefined, // 下达需要的参数
    };
  }

  UNSAFE_componentWillMount() {
    const { type, types } = this.props;
    this.props.onRef(this);
    let data = {};
    if (types) {
      data = config.statusControl.find((item) => item.key == 5);
    } else {
      data = config.statusControl.find((item) => item.key == type);
    }
    this.setState({
      statusControl: data,
    });
  }

  componentDidMount() {
    if (this.props.type == 1 || this.props.type == 2) {
      // 组合试算、详情不需要uuid  簿记单独请求 不再这里请求
      const uid = uniqueKey();
      uid.then((r) => {
        this.setState({ uid: r });
      });
    }
  }

  // 组件销毁，清空model内容
  // componentWillUnmount() {
  //     this.reset()
  // }

  UNSAFE_componentWillReceiveProps(nextProps) {
    const { types } = this.props;
    if (nextProps.initValue) {
      const init = nextProps.initValue.trade15;
      const tradingCode = types ? init.tradingcode : `${init.exchangecode}-${init.tradingcode}`;
      if (nextProps.initValue.id && nextProps.edit == true) {
        this.setState({
          id: nextProps.initValue.id,
          id2: init.id,
          secuabbr: init.secuabbr,
        });
      }
      this.setState({
        productId: init.productid,
        portfolioId: init.portfolioid,
        tradingCode,
        exchangeCode: init.exchangecode,
        orderSide: init.orderSide,
        direction: init.direction,
        type: init.type,
        price: init.price,
        amount: init.amount,
        totalPrice: init.totalPrice,
        remark: init.remark,
        realOrderPrice: init.price,
        realOrderQty: init.amount,
        firstExpenses: init.firstExpenses,
        investmentType: init.investmentType,
        // fee: init.fee,
      });
    }
  }

  // 费用自动计算
  changeFee = (type, data) => {
    const {
      form: { setFieldsValue },
    } = this.formGroupThis.props;
    if (this.props.type == 5 || this.props.types == 1) return; // 详情不计算
    setTimeout(() => {
      if (data == undefined) {
        setFieldsValue({ fee: undefined });
        if (type == 'tradingCode') {
          this.setState({ feeData: { ...this.state.feeData, tradingCode: undefined, exchangecode: undefined } });
        } else if (type == 'productId') {
          this.setState({ feeData: { ...this.state.feeData, productId: undefined, portfolioid: undefined } });
        } else {
          this.setState({ feeData: { ...this.state.feeData, [type]: undefined } });
        }
      } else if (type == 'tradingCode') {
        this.setState({ feeData: { ...this.state.feeData, tradingCode: data.tradingCode, exchangecode: data.exchangeCode } }, () => {
          const fee = calculateFee(this.state.feeData);
          fee.then((r) => {
            setFieldsValue({ fee: r });
          });
        });
      } else {
        this.setState({ feeData: { ...this.state.feeData, [type]: data } }, () => {
          const fee = calculateFee(this.state.feeData);
          fee.then((r) => {
            setFieldsValue({ fee: r });
          });
        });
      }
    }, 100);
  };

  // 组合改变
  groupOnChange = (value) => {
    const {
      form: { getFieldValue },
    } = this.props;
    // 得到组合名称
    this.setState({
      portfolioName: value ? value?.info?.portfolioName : undefined,
    });
    // 指令下达模块时，需要获取可用资金和可用持仓
    if (this.props.type && this.props.type == '1') {
      this.props.dispatch({
        type: 'stockOrderM/save',
        payload: {
          positionInfo: {
            0: '--',
            1: '--',
          },
          positionInfo2: '--',
        },
      });
      if (value) {
        this.props.dispatch({
          // 校验组合下是否有组合配置
          type: 'isAccountConfiguredM/queryIsAccountConfigured',
          payload: {
            portId: value.key,
          },
          callback: (data) => {
            if (data.result) {
              this.setState({
                isCanOrder: true,
              });
            } else {
              this.setState({
                isCanOrder: false,
              });
              message.warning(data.msg);
            }
          },
        });
      } else {
        this.setState({
          isCanOrder: true,
        });
      }
      if (value) {
        const tradingCode = getFieldValue('tradingCode');
        const exchangeCode = getFieldValue('exchangeCode');
        const newValue = value ? value.key : value;
        this.props.dispatch({
          type: 'stockOrderM/queryFund',
          payload: {
            nodeId: newValue,
            code: 'kk',
          },
        });

        if (tradingCode && exchangeCode) {
          this.props.dispatch({
            type: 'stockOrderM/getPosition',
            payload: {
              code: newValue,
              exchangeCode,
              tradingCode: tradingCode.split('-')[1],
            },
          });
        }
      }
    }
    if (this.props.changeType) {
      this.props.changeType(value);
    }
  };

  // 证券代码改变时根据交易方向更改投资类型
  changeinvestmentType = () => {
    const {
      form: { getFieldValue, setFieldsValue },
    } = this.formGroupThis.props;
    if (getFieldValue('orderSide') == 2) {
      setFieldsValue({
        investmentType: this.props.investmentType,
      });
    } else {
      setFieldsValue({
        investmentType: 'FVTPL',
      });
    }
  };

  // 证券代码改变
  securitiesCodeChange = (e) => {
    const {
      form: { setFieldsValue, getFieldValue },
    } = this.formGroupThis.props;
    if (e) {
      this.setState({
        secuabbr: e.secuabbr,
      });
      setFieldsValue({
        exchangeCode: e.exchangeCode,
      });
      if (this.props.changeCode) {
        this.props.changeCode(e);
      }

      this.props.dispatch({
        type: 'stockOrderM/save',
        payload: {
          flag: false,
        },
      });
    } else {
      this.setState({
        secuabbr: null,
      });
      setFieldsValue({
        exchangeCode: null,
      });
    }

    // 指令下达模块时，需要获取股票信息
    if (this.props.type && (this.props.type == '1' || this.props.type == '3' || this.props.type == 11)) {
      if (e && e.tradingCode && e.exchangeCode) {
        const code = getFieldValue('portfolioId');

        // 获取持仓信息
        if (code) {
          // eslint-disable-next-line eqeqeq
          // 只有在指令模块
          if (this.props.type == '1')
            this.props.dispatch({
              type: 'stockOrderM/getPosition',
              payload: {
                code,
                exchangeCode: e.exchangeCode,
                tradingCode: e.tradingCode,
              },
            });
        }

        // 获取股票信息
        this.props
          .dispatch({
            type: 'stockOrderM/getStock1',
            payload: {
              exchangeCode: e.exchangeCode,
              tradingCode: e.tradingCode,
            },
          })
          .then((res) => {
            if (res == '停牌') {
              this.setState({
                status: true,
              });
            } else {
              this.setState({
                status: false,
              });
            }
          });

        // 获取股票信息
        this.props.dispatch({
          type: 'stockOrderM/getStock2',
          payload: {
            exchangeCode: e.exchangeCode,
            tradingCode: e.tradingCode,
          },
        });
      } else {
        // 点击证券代码后面的小叉号，清空了证券代码
        //   1.股票信息暂无数据
        this.props.dispatch({
          type: 'stockOrderM/save',
          payload: {
            stockInfor1: {
              code: '--',
              secucode: '--',
              secuabbr: '--',
              comChiname: '--',
              sindunameWind: '--',
            },
            stockInfor2: {
              status: null,
              lastpx: '--',
              highpx: '--',
              lowpx: '--',
              upDownPrices: '--',
              upDownRange: '--',
              totalvolumetrade: '--',
              totalvaluetrade: '--',
              maxpx: '--',
              minpx: '--',
            },
            flag: true,
          },
        });
        this.props.dispatch({
          type: 'stockOrderM/save',
          payload: {
            positionInfo2: '--',
          },
        });
        this.setState({
          status: false,
        });
        setFieldsValue({
          price: null,
        });
        if (this.props.changeCode) {
          this.props.changeCode(e);
        }
      }
    }
  };

  // 交易类型切换
  jylxOnchange = (e) => {
    const {
      form: { setFieldsValue, getFieldValue },
    } = this.formGroupThis.props;
    const {
      stockOrderM: { stockInfor2 },
    } = this.props;
    const orderSide = getFieldValue('orderSide');
    const amount = getFieldValue('amount');
    if (e == '2') {
      this.setState(
        {
          priceDisabled: true,
        },
        () => {
          if (orderSide == '1') {
            if (stockInfor2.maxpx != '--') {
              setFieldsValue({
                price: Number(stockInfor2.maxpx).toFixed(2),
                totalPrice: amount ? Number(amount * Number(stockInfor2.maxpx)).toFixed(2) : null,
              });
              // this.changeFee('price', amount ? Number(amount * Number(stockInfor2.maxpx)).toFixed(2) : undefined);
            }
          }
          if (orderSide == '2') {
            if (stockInfor2.minpx != '--') {
              setFieldsValue({
                price: Number(stockInfor2.minpx).toFixed(2),
                totalPrice: amount ? Number(amount * Number(stockInfor2.minpx)).toFixed(2) : null,
              });
              // this.changeFee('price', amount ? Number(amount * Number(stockInfor2.maxpx)).toFixed(2) : undefined);
            }
          }
        },
      );
    } else {
      this.setState({
        priceDisabled: false,
      });
    }
  };

  // 委托方向切换
  wtfxOnChange = (e) => {
    const {
      form: { setFieldsValue, getFieldValue },
    } = this.formGroupThis.props;
    const {
      stockOrderM: { stockInfor2 },
    } = this.props;
    if (this.props.type == 5 || this.props.types == 1) return;
    const type = getFieldValue('type');
    const amount = getFieldValue('amount');
    // this.changeFee('orderside', e ? e : undefined);
    if (e == '1') {
      setFieldsValue({
        investmentType: 'FVTPL',
      });
    } else {
      setFieldsValue({
        investmentType: this.props.investmentType,
      });
    }
    if (type == '2') {
      if (e == '1') {
        if (stockInfor2.maxpx != '--') {
          setFieldsValue({
            price: Number(stockInfor2.maxpx).toFixed(2),
            totalPrice: amount ? Number(amount * Number(stockInfor2.maxpx)).toFixed(2) : null,
          });
          // this.changeFee('price', amount ? Number(amount * Number(stockInfor2.maxpx)).toFixed(2) : undefined);
        }
      }

      if (e == '2') {
        if (stockInfor2.minpx != '--') {
          setFieldsValue({
            price: Number(stockInfor2.minpx).toFixed(2),
            totalPrice: amount ? Number(amount * Number(stockInfor2.minpx)).toFixed(2) : null,
          });
          // this.changeFee('price', amount ? Number(amount * Number(stockInfor2.minpx)).toFixed(2) : undefined);
        }
      }
    }
    this.setState({ orderSideType: e });
  };

  // 委托方向切换

  // 计算金额
  calculateAmount = (value, type) => {
    const {
      form: { setFieldsValue, getFieldValue },
    } = this.formGroupThis.props;
    const amount = type == 'amount' ? value : getFieldValue('amount');
    const realOrderQty = type == 'realOrderQty' ? value : getFieldValue('realOrderQty');
    const price = type == 'price' ? value : getFieldValue('price');
    const realOrderPrice = type == 'realOrderPrice' ? value : getFieldValue('realOrderPrice');
    const firstExpenses = type == 'firstExpenses' ? value : getFieldValue('firstExpenses');

    if ((amount && price) || (amount && price == 0) || (amount == 0 && price)) {
      setFieldsValue({
        totalPrice: Number(firstExpenses ? amount * price + firstExpenses : amount * price).toFixed(2),
      });
      // this.changeFee('price', Number(firstExpenses ? amount * price + firstExpenses : amount * price).toFixed(2));
    }

    if ((realOrderQty && realOrderPrice) || (realOrderQty && realOrderPrice == 0) || (realOrderQty == 0 && realOrderPrice)) {
      setFieldsValue({
        totalPrice: Number(firstExpenses ? realOrderQty * realOrderPrice + firstExpenses : realOrderQty * realOrderPrice).toFixed(2),
      });
      // this.changeFee('price', Number(firstExpenses ? realOrderQty * realOrderPrice + firstExpenses : realOrderQty * realOrderPrice).toFixed(2));
    }

    // 0和负数特殊处理，金额归零
    if (amount < 0 || realOrderQty < 0 || price < 0 || realOrderPrice < 0) {
      setFieldsValue({
        totalPrice: fixedNum(0, 2),
      });
      // this.changeFee('price', undefined);
    }
  };

  // 恢复默认状态
  reset = () => {
    // 清空字段信息
    const {
      form: { resetFields },
    } = this.formGroupThis.props;
    resetFields([
      'productId',
      'portfolioId',
      'tradingCode',
      'exchangeCode',
      'orderSide',
      'direction',
      'type',
      'price',
      'amount',
      'totalPrice',
      'remark',
      'realOrderPrice',
      'realOrderQty',
      'firstExpenses',
      'investmentType',
      'fee',
    ]);

    // 指令下达模块恢复默认值
    if (this.props.type && (this.props.type == '1' || this.props.type == '3')) {
      // 股票详情到默认值
      this.props.dispatch({
        type: 'stockOrderM/save',
        payload: {
          stockInfor1: {
            code: '--',
            secucode: '--',
            secuabbr: '--',
            comChiname: '--',
            sindunameWind: '--',
          },
          stockInfor2: {
            status: null,
            lastpx: '--',
            highpx: '--',
            lowpx: '--',
            upDownPrices: '--',
            upDownRange: '--',
            totalvolumetrade: '--',
            totalvaluetrade: '--',
            maxpx: '--',
            minpx: '--',
          },
          flag: true,
        },
      });

      // 资金/持仓可用到默认值
      this.props.dispatch({
        type: 'stockOrderM/save',
        payload: {
          positionInfo: {
            0: '--',
            1: '--',
          },
          positionInfo2: '--',
        },
      });
      if (this.props.changeType) {
        this.props.changeType();
      }
      if (this.props.changeCode) {
        this.props.changeCode();
      }
    }
    // 更新组合代码
    this.props.onChangePortfolioCode();

    // 取消指令下达disabled
    this.setState({
      status: false,
      priceDisabled: false,
      isCanOrder: true, // 恢复默认可下达
      productCode: undefined, // 产品code
      portfolioCode: undefined, // 组合code
      portfolioName: undefined, // 组合名称
      productName: undefined, // 产品名称
    });

    // id置空
    this.setState({
      id: null,
    });
  };

  save = () => {
    const { type } = this.props;

    const data = this.getInfo();
    if (JSON.stringify(data) != '{}') {
      const datas = {};
      datas.trade15 = data;
      (datas.trade15.productid = data.productId),
        (datas.trade15.portfolioid = data.portfolioId),
        (datas.trade15.tradingcode = data.tradingCode),
        (datas.trade15.exchangecode = data.exchangeCode);
      if (type == '1') {
        if (!this.state.isCanOrder && this.props.type == 1) {
          // 在点击“下达”时，若标记指示未配置指令，则提示用户“该组合为配置指令，无法下发指令。
          message.warning(this.props.errorSetMsg);
          return;
        }
        this.setState({ query: datas }, () => {
          this.setState({ isShow: true });
        });
      } else {
        this.addData();
      }
    }
  };

  // 二次确认点击确定
  handleOk = () => {
    this.addData();
  };

  // 二次确认点击取消
  handleCancel = () => {
    this.setState({
      isShow: false,
    });
  };

  // 二次确认model框
  showModel = () => {
    const { query, isShow } = this.state;
    const { loading } = this.props;
    const modalProps = {
      visible: isShow,
      title: '确认下达',
      width: 1500,
    };
    return (
      <div style={{ marginLeft: '200px' }}>
        <Modal {...modalProps} onOk={this.handleOk} onCancel={this.handleCancel} confirmLoading={loading.effects['stockOrderM/saveInstruction'] === true}>
          {this.props.showTable(query)}
        </Modal>
      </div>
    );
  };

  // 获取校验并获取表单的值
  getInfo = () => {
    const {
      form: { validateFields },
    } = this.formGroupThis.props;
    const query = {};
    validateFields(
      [
        'productId',
        'portfolioId',
        'tradingCode',
        'exchangeCode',
        'orderSide',
        'direction',
        'type',
        'price',
        'amount',
        'totalPrice',
        'remark',
        'realOrderPrice',
        'realOrderQty',
        'firstExpenses',
        'investmentType',
        'fee',
      ],
      (err, fieldsValue) => {
        if (!err) {
          (query.productId = fieldsValue.productId),
            (query.portfolioId = fieldsValue.portfolioId),
            (query.tradingCode = fieldsValue.tradingCode),
            (query.exchangeCode = fieldsValue.exchangeCode),
            (query.orderSide = fieldsValue.orderSide),
            (query.direction = fieldsValue.direction),
            (query.type = fieldsValue.type),
            (query.price = fieldsValue.price),
            (query.amount = fieldsValue.amount),
            (query.totalPrice = fieldsValue.totalPrice),
            (query.remark = fieldsValue.remark),
            (query.investmentType = fieldsValue.investmentType),
            (query.fee = 0); // 费用计算逻辑未完全梳理清楚，后续用户有真正需求时再添加费用计算相关逻辑
        }
      },
    );
    return query;
  };

  // 指令或簿记下达
  addData = () => {
    const {
      form: { validateFields },
    } = this.formGroupThis.props;
    const {
      stockOrderM: { positionInfo2, positionInfo, stockInfor2 },
      dispatch,
      user,
    } = this.props;

    validateFields(
      [
        'productId',
        'portfolioId',
        'tradingCode',
        'exchangeCode',
        'orderSide',
        'direction',
        'type',
        'price',
        'amount',
        'totalPrice',
        'remark',
        'realOrderPrice',
        'realOrderQty',
        'firstExpenses',
        'investmentType',
        'fee',
      ],
      (err, fieldsValue) => {
        if (err) return;

        //  下达指令的校验
        if (this.props.type == '1') {
          //  融资----卖出---2
          //  融券----买入---1
          // （3）指令下达时（簿记不必校验），委托数量必须是100的整数倍，或者是0股卖出（条件：交易方向是卖出、数量与持仓T+0可用相等）；
          // （4）指令下达时（簿记不必校验），交易方向为卖出时，校验委托数量小于等于T+0持仓可用；
          // （5）指令下达时（簿记不必校验），交易方向为买入时，校验金额小于资金T+1可用；
          // （6）指令下达时（簿记不必校验），买入或卖出，委托价格在股票最低价和最高价之间。

          if (fieldsValue.price) {
            if (Number(fieldsValue.price) > Number(stockInfor2.maxpx) || Number(fieldsValue.price) < Number(stockInfor2.minpx)) {
              message.warning('委托价格在股票最低价和最高价之间');
              return;
            }
          }

          if (fieldsValue.amount) {
            if (fieldsValue.orderSide == '1') {
              const amount = fieldsValue.amount.toString();
              const reg = /^[1-9]\d*00$/;
              const r = amount.match(reg);
              if (r == null || Number(fieldsValue.amount) == 0) {
                message.warning('委托数量必须是100的整数倍');
                return;
              }
            } else if (Number(fieldsValue.amount) != Number(positionInfo2)) {
              const amount = fieldsValue.amount.toString();
              const reg = /^[1-9]\d*00$/;
              const r = amount.match(reg);
              if (Number(fieldsValue.amount) > Number(positionInfo2) || positionInfo2 == '--') {
                message.warning('委托数量需要小于等于T+0持仓可用');
                return;
              }
              if (r == null || Number(fieldsValue.amount) == 0) {
                message.warning('委托数量必须是100的整数倍');
                return;
              }
            }
          }

          if (Number(fieldsValue.amount) == 0) {
            message.warning('委托数量不能为0');
            return;
          }

          if (fieldsValue.totalPrice) {
            if (fieldsValue.orderSide == '1') {
              if (Number(fieldsValue.totalPrice) >= Number(positionInfo[1]) || positionInfo[1] == '--') {
                message.warning('金额需要小于资金T+1可用');
                return;
              }
            }
          }
        }

        if (this.props.type == '3' || this.props.type == 11) {
          if (Number(fieldsValue.realOrderQty) == 0) {
            message.warning('成交数量不能为0');
            return;
          }
        }
        // 簿记保存修改
        if (this.props.type == '3' || this.props.type == '4') {
          this.saveOrderNew(fieldsValue);
          return;
        }

        const value = {
          portfolioId: fieldsValue.portfolioId,
          portfolioInfoId: fieldsValue.portfolioId,
          productId: fieldsValue.productId,
          type: 15,
          userId: localStorage.getItem('antd-pro-userId'),
          userName: user.currentUser.name,
          uid: this.state.uid,
          trade15: {
            portfolioid: fieldsValue.portfolioId,
            productid: fieldsValue.productId,
            exchangecode: fieldsValue.exchangeCode,
            tradingcode: fieldsValue.tradingCode ? fieldsValue.tradingCode.split('-')[1] : null,
            orderSide: fieldsValue.orderSide,
            direction: fieldsValue.direction,
            type: fieldsValue.type,
            price: fieldsValue.price,
            amount: fieldsValue.amount,
            realOrderPrice: fieldsValue.realOrderPrice,
            realOrderQty: fieldsValue.realOrderQty,
            totalPrice: fieldsValue.totalPrice,
            remark: fieldsValue.remark,
            secuabbr: this.state.secuabbr,
            investmentType: fieldsValue.investmentType,
            fee: 0, // 费用计算逻辑未完全梳理清楚，后续用户有真正需求时再添加费用计算相关逻辑
          },
        };

        const value1 = {
          portfolioId: fieldsValue.portfolioId,
          portfolioInfoId: fieldsValue.portfolioId,
          productId: fieldsValue.productId,
          type: 15,
          userId: localStorage.getItem('antd-pro-userId'),
          userName: user.currentUser.name,
          uid: this.state.uid,
          trade15: {
            portfolioid: fieldsValue.portfolioId,
            productid: fieldsValue.productId,
            exchangecode: fieldsValue.exchangeCode,
            tradingcode: fieldsValue.tradingCode ? fieldsValue.tradingCode.split('-')[1] : null,
            orderSide: fieldsValue.orderSide,
            direction: fieldsValue.direction,
            type: fieldsValue.type,
            price: fieldsValue.realOrderPrice,
            amount: fieldsValue.realOrderQty,
            totalPrice: fieldsValue.totalPrice,
            remark: fieldsValue.remark,
            secuabbr: this.state.secuabbr,
            investmentType: fieldsValue.investmentType,
            fee: 0, // 费用计算逻辑未完全梳理清楚，后续用户有真正需求时再添加费用计算相关逻辑
          },
        };

        // 触发loading
        this.setState({
          btnLoading: true,
        });

        // 指令下达
        if (this.props.type == '1') {
          this.props
            .dispatch({
              type: 'stockOrderM/saveInstruction',
              payload: {
                ...value,
              },
            })
            .then((res) => {
              // 解除loading
              this.setState({
                btnLoading: false,
              });
              if (res && res.success) {
                // 恢复默认状态
                this.reset();
                this.securitiesCodeChange();
                this.groupOnChange();
                this.setState({ isShow: false });
              }
              if (this.props.type == 1 || this.props.type == 2) {
                const uid = uniqueKey();
                // eslint-disable-next-line promise/no-nesting
                uid.then((r) => {
                  this.setState({ uid: r });
                });
              }
            });
        }
        if (this.props.type == '11') {
          // 组合试算
          value1.method = '0';
          if (this.props.edit) {
            value1.id = this.state.id;
            value1.trade15.id = this.state.id2;
          }
          this.props
            .dispatch({
              type: 'portfolioTrialAddM/stockSave',
              payload: {
                ...value1,
              },
            })
            .then((res) => {
              // 解除loading
              this.setState({
                btnLoading: false,
              });
              if (res && res.success) {
                // 恢复默认状态
                this.reset();
                // 重新获取表格数据，关闭模态框
                this.props.rehandleSearch();
              }
            });
        }
      },
    );
  };

  // 簿记下达 新接口
  saveOrderNew = (fieldsValue) => {
    const { uid, productCode, portfolioCode, secuabbr, portfolioName, productName } = this.state;
    const { dispatch } = this.props;
    this.setState({
      orderParams: {
        instructionType: '0', // 簿记填0
        portfolioId: fieldsValue.portfolioId, // 组合id
        productId: fieldsValue.productId, // 产品id
        productCode, // 产品code
        productName, // 产品名称
        portfolioCode, // 组合code
        portfolioName, // 组合名称
        tradingCode: fieldsValue.tradingCode ? fieldsValue.tradingCode.split('-')[1] : null, // 证券代码
        tradingName: secuabbr, // 证券名称
        exchangeCode: fieldsValue.exchangeCode, // 交易所代码
        tradeDir: fieldsValue.orderSide, // 交易方向
        tradeMode: fieldsValue.type, // 交易类型
        price: fieldsValue.realOrderPrice, // 价格
        num: fieldsValue.realOrderQty, // 数量
        amount: Number(fieldsValue.totalPrice), // 金额
        investmentType: fieldsValue.investmentType, // 投资类型
        remark: fieldsValue.remark,
      },
      visibleStep: true, // 开始loading
    });
  };

  // 取消
  cancel = () => {
    // 恢复默认状态
    this.reset();
    // 簿记取消
    if (this.props.type == '3' || this.props.type == '4' || this.props.type == '5' || this.props.type == 11) {
      // 关闭模态框
      this.props.rehandleSearch2();
    }
  };

  // 试算按钮点击
  trialOnClick = () => {
    const { dispatch, user } = this.props;
    const {
      form: { validateFields },
    } = this.formGroupThis.props;

    validateFields(
      [
        'productId',
        'portfolioId',
        'tradingCode',
        'exchangeCode',
        'orderSide',
        'direction',
        'type',
        'price',
        'amount',
        'totalPrice',
        'remark',
        'realOrderPrice',
        'realOrderQty',
        'firstExpenses',
        'investmentType',
      ],
      (err, fieldsValue) => {
        if (err) return;

        if (this.props.type == '3' || this.props.type == 11) {
          if (Number(fieldsValue.realOrderQty) == 0) {
            message.warning('成交数量不能为0');
            return;
          }
        }

        const value1 = {
          portfolioId: fieldsValue.portfolioId,
          portfolioInfoId: fieldsValue.portfolioId,
          productId: fieldsValue.productId,
          type: 15,
          userId: localStorage.getItem('antd-pro-userId'),
          userName: user.currentUser.name,
          productCode: this.state.productCode, // 产品code
          portfolioCode: this.state.portfolioCode, // 组合code
          tenant: user.currentUser.tenant, // 租户code
          businessType: '15',
          trade15: {
            portfolioid: fieldsValue.portfolioId,
            productid: fieldsValue.productId,
            exchangecode: fieldsValue.exchangeCode,
            tradingcode: fieldsValue.tradingCode ? fieldsValue.tradingCode.split('-')[1] : null,
            orderSide: fieldsValue.orderSide,
            direction: fieldsValue.direction,
            type: fieldsValue.type,
            price: fieldsValue.realOrderPrice,
            amount: fieldsValue.realOrderQty,
            totalPrice: fieldsValue.totalPrice,
            remark: fieldsValue.remark,
            secuabbr: this.state.secuabbr,
            investmentType: fieldsValue.investmentType,
          },
        };

        // 簿记保存修改
        if (this.props.type == '3' || this.props.type == '4') {
          value1.method = '0';
          if (this.props.edit) {
            value1.id = this.state.id;
            value1.trade15.id = this.state.id2;
          }
        }
        this.setState({ trailModel: true }, () => {
          dispatch({
            type: 'trailM/trialData',
            payload: value1,
            callback: (res) => {
              if (res) {
                this.setState({
                  trailColumns: res.columns,
                  trailDataSource: res.dataSource,
                });
              } else {
                this.setState({
                  trailColumns: [],
                  trailDataSource: [],
                });
              }
            },
          });
        });
      },
    );
  };

  // 试算结果列表优化
  trailColumnsChange = (data) => {
    if (data) {
      data?.map((item) => {
        if (item.key == 'ruleDesc') {
          item.ellipsis = true;
        } else {
          item.width = '125px';
        }
      });
    }
    return data;
  };

  // 试算结果
  showTrail = () => {
    const { trailModel, trailColumns, trailDataSource } = this.state;
    const newTrailColumns = this.trailColumnsChange(trailColumns);
    return (
      <ModalC
        visible={trailModel}
        title='试算结果'
        width={1200}
        onOk={() => {
          this.setState({ trailModel: false });
        }}
        onCancel={() => {
          this.setState({ trailModel: false });
        }}
      >
        <TableC
          columns={newTrailColumns}
          dataSource={trailDataSource}
          loading={this.props.loading.effects['trailM/trialData'] === true}
          scroll={{ y: '231px' }}
          rowKey='id'
          hidePage={true}
        />
      </ModalC>
    );
  };

  // 获取组合code
  portfolioCode = (e) => {
    if (e) {
      this.setState({ portfolioCode: e });
    } else this.setState({ portfolioCode: undefined });
    // 更新组合代码
    this.props.onChangePortfolioCode(e || undefined);
  };

  // 获取产品code
  productCode = (e) => {
    if (e) {
      this.setState({ productCode: e });
    } else this.setState({ productCode: undefined });
  };

  // 下达成功之后  清空页面
  handleSuccess = () => {
    this.setState({
      visibleStep: false,
    });
    // 恢复默认状态
    this.reset();
  };

  // 下达失败 用户主动点击关闭 处理逻辑
  handleError = (type) => {
    this.setState({
      visibleStep: false,
    });
    if (type) {
      // 更新可用持仓 还是可用资金
      this.props.changeTimeStamp(type == 1 ? 'timeStamp1' : 'timeStamp2');
    }
  };

  render() {
    const { statusControl, orderParams, visibleStep } = this.state;
    const typeData =
      this.props.type == '3'
        ? [{ title: '限价', value: '1' }]
        : [
            { title: '限价', value: '1' },
            { title: '市价', value: '2' },
          ];
    return (
      <>
        <FormGroup
          dataSource={[
            {
              disabled: statusControl.productId.disabled,
              type: DATA_ENTRY.PRODUCTGROUPSEP,
              initialValue: [this.state.productId ? this.state.productId : undefined, this.state.portfolioId ? this.state.portfolioId : undefined],
              title: ['产品', '组合'],
              authority: 'write',
              multipleGroup: false,
              dataIndex: ['productId', 'portfolioId'],
              rules: [[{ required: statusControl.productId.rule, message: '请选择产品' }], [{ required: statusControl.portfolioId.rule, message: '请选择组合' }]],
              groupOnChange: (e) => {
                this.groupOnChange(e);
                this.portfolioCode(e ? e.info.portfolioCode : undefined); // 向外抛出组合code
                // this.changeFee('portfolioid', e?.key);
              },
              productOnChange: (e) => {
                // 得到产品名称
                this.setState({
                  productName: e ? e?.info?.portfolioName : undefined,
                });
                this.productCode(e ? e.info.portfolioCode : undefined); // 向外抛出产品code
                // this.changeFee('productId', e?.key);
              },
              allowClear: false,
              exist: 1,
              span: 16,
              controlLabelSpan: 6,
              tradeModel: this.props.type == 1 || this.props.type == 3 ? ['BOOKKEEPING_MODE', 'COMMAND_MODE'] : undefined, // 不包含估值解析和估值对接的产品
            },
            {
              disabled: statusControl.tradingCode.disabled,
              type: DATA_ENTRY.SECURITIESCODE,
              dataIndex: 'tradingCode',
              queryItems: this.state.queryItems,
              initialValue: this.state.tradingCode ? this.state.tradingCode : null,
              codeType: codeType.gp,
              rules: [{ required: statusControl.tradingCode.rule, message: '请选择证券代码' }],
              title: '证券代码',
              onChange: (e) => {
                this.securitiesCodeChange(e);
                // this.changeFee('tradingCode', e ? e : undefined);
              },
              span: 8,
              controlLabelSpan: 6,
            },
            {
              title: '交易市场',
              dataIndex: 'exchangeCode',
              type: DATA_ENTRY.TRADINGMARKET,
              initialValue: this.state.exchangeCode ? this.state.exchangeCode : null,
              rules: [{ required: statusControl.exchangeCode.rule, message: '请选择交易所' }],
              disabled: statusControl.exchangeCode.disabled,
              span: 8,
              controlLabelSpan: 6,
              onRef: (ref) => (this.formGroupThis = ref),
            },
            {
              title: '投资类型',
              dataIndex: 'investmentType',
              type: DATA_ENTRY.SELECT,
              initialValue: this.state.investmentType ? this.state.investmentType : 'FVTPL',
              disabled: statusControl.investmentType.disabled ? statusControl.investmentType.disabled : this.state.orderSideType == 2,
              dataSource: investmentTypeData,
              allowClear: true,
              rules: [{ required: false, message: '请选择' }],
              span: 8,
              controlLabelSpan: 6,
            },
            {
              title: '委托方向', // 显示名称
              dataIndex: 'orderSide', // Form识别的Item ID
              businessType: '15',
              type: DATA_ENTRY.TRADINGDIRECT,
              initialValue: this.state.orderSide ? this.state.orderSide : null,
              rules: [{ required: statusControl.orderSide.rule, message: '请选择委托方向' }],
              disabled: statusControl.orderSide.disabled,
              onChange: (e) => this.wtfxOnChange(e?.value),
              allowClear: false,
              span: 8,
              controlLabelSpan: 6,
            },
            {
              title: '交易类型', // 显示名称
              dataIndex: 'type', // Form识别的Item ID
              type: DATA_ENTRY.SELECT,
              initialValue: this.state.type ? this.state.type : null,
              rules: [{ required: statusControl.type.rule, message: '请选择交易类型' }],
              disabled: statusControl.type.disabled,
              dataSource: typeData,
              onChange: (e) => this.jylxOnchange(e),
              span: 8,
              controlLabelSpan: 6,
            },
            ...(statusControl.price.show
              ? [
                  {
                    onChange: (val) => this.calculateAmount(val, 'price'),
                    dataIndex: 'price',
                    type: DATA_ENTRY.INPUTNUMBER,
                    disabled: statusControl.price.disabled || this.state.priceDisabled,
                    initialValue: this.state.price ? this.state.price : null,
                    min: 0.01,
                    max: 999999999999,
                    splitStyle: true,
                    precision: 2,
                    title: '委托价格',
                    unit: '元',
                    rules: [{ required: statusControl.price.rule, message: '请输入委托价格' }],
                    span: 8,
                    controlLabelSpan: 6,
                  },
                ]
              : []),
            ...(statusControl.realOrderPrice.show
              ? [
                  {
                    onChange: (val) => this.calculateAmount(val, 'realOrderPrice'),
                    dataIndex: 'realOrderPrice',
                    type: DATA_ENTRY.INPUTNUMBER,
                    disabled: statusControl.price.disabled,
                    initialValue: this.state.realOrderPrice,
                    splitStyle: true,
                    min: 0.01,
                    max: 999999999999,
                    precision: 2,
                    title: '成交价格',
                    unit: '元',
                    rules: [{ required: statusControl.realOrderPrice.rule, message: '请输入成交价格' }],
                    span: 8,
                    controlLabelSpan: 6,
                  },
                ]
              : []),
            ...(statusControl.amount.show
              ? [
                  {
                    dataIndex: 'amount',
                    type: DATA_ENTRY.INPUTNUMBER,
                    disabled: statusControl.amount.disabled,
                    splitStyle: true,
                    initialValue: this.state.amount ? this.state.amount : null,
                    min: 0,
                    max: 999999999999,
                    precision: 0,
                    title: '委托数量',
                    unit: '股',
                    onChange: (val) => this.calculateAmount(val, 'amount'),
                    rules: [
                      { required: statusControl.amount.rule, message: '请输入委托数量' },
                      { pattern: /^[+-]?(\d){1,}00$/, message: '请输入100的倍数' },
                    ],
                    span: 8,
                    controlLabelSpan: 6,
                  },
                ]
              : []),
            ...(statusControl.realOrderQty.show
              ? [
                  {
                    dataIndex: 'realOrderQty',
                    type: DATA_ENTRY.INPUTNUMBER,
                    disabled: statusControl.realOrderQty.disabled,
                    initialValue: this.state.realOrderQty,
                    min: 0,
                    max: 999999999999,
                    precision: 0,
                    title: '成交数量',
                    unit: '股',
                    onChange: (val) => this.calculateAmount(val, 'realOrderQty'),
                    rules: [{ required: statusControl.realOrderQty.rule, message: '请输入成交数量' }],
                    span: 8,
                    controlLabelSpan: 6,
                  },
                ]
              : []),
            ...(statusControl.firstExpenses.show
              ? [
                  {
                    dataIndex: 'firstExpenses',
                    title: '一级费用',
                    type: DATA_ENTRY.INPUT,
                    initialValue: this.state.firstExpenses ? this.state.firstExpenses : null,
                    rules: [{ required: statusControl.firstExpenses.rule, message: '请输入一级费用' }],
                    disabled: statusControl.firstExpenses.disabled,
                    suffix: '元',
                    span: 8,
                    controlLabelSpan: 6,
                  },
                ]
              : []),
            {
              title: '金额',
              dataIndex: 'totalPrice',
              disabled: statusControl.totalPrice.disabled,
              type: DATA_ENTRY.INPUTNUMBER,
              initialValue: this.state.totalPrice ? this.state.totalPrice : null,
              min: 0,
              max: 999999999999,
              splitStyle: true,
              precision: 2,
              unit: '元',
              rules: [{ required: statusControl.totalPrice.rule, message: '请输入额' }],
              span: 8,
              controlLabelSpan: 6,
            },
            // {
            //     title: '费用',
            //     dataIndex: 'fee',
            //     placeholder: "请输入",
            //     type: DATA_ENTRY.INPUTNUMBER,
            //     min: 0,
            //     precision: 2,
            //     initialValue: this.state.fee ? this.state.fee : '',
            //     splitStyle: true,
            //     disabled: statusControl.fee.disabled,
            //     unit: '元',
            //     span: 8,
            // controlLabelSpan:6,
            // },
            {
              dataIndex: 'remark',
              type: DATA_ENTRY.INPUT,
              title: '备注',
              disabled: statusControl.remark.disabled,
              initialValue: this.state.remark ? this.state.remark : null,
              rules: [{ required: statusControl.remark.rule }],
              placeholder: '请输入',
              showTextArea: true,
              autosize: { minRows: 2, maxRows: 2 },
              span: 24,
              controlLabelSpan: 2,
            },
          ]}
          autoLayout={false}
        />
        <div>{this.state.isShow ? <div>{this.showModel()}</div> : null}</div>
        {this.props.type == 5 || this.props.types == 1 ? null : (
          <Row style={{ paddingBottom: '6px' }}>
            <Col span={24} style={{ textAlign: 'right' }}>
              {statusControl.button.release && (
                <PrimaryC title='下达' disabled={this.state.status} loading={this.state.btnLoading} style={{ margin: '10px' }} onClick={() => this.save('指令')} />
              )}

              {/* {statusControl.button.trial && <PrimaryC
                        loading={this.props.loading.effects['trailM/trialData'] === true}
                        onClick={() => this.trialOnClick()}
                        title={'试算'}
                        style={{ marginRight: "10px" }}
                    />} */}
              {statusControl.button.save && <PrimaryC title='确定' style={{ margin: '10px' }} loading={this.state.btnLoading} onClick={() => this.save('簿记')} />}

              {statusControl.button.cancle && <PrimaryGhostC title='取消' style={{ margin: '10px' }} onClick={() => this.cancel()} />}
            </Col>
          </Row>
        )}

        {this.state.trailModel && this.showTrail()}
        {visibleStep ? <OrderC visible={visibleStep} handleSuccess={this.handleSuccess} handleError={this.handleError} params={orderParams} tradeType={'stockBj'} /> : null}
      </>
    );
  }
}
